﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.SessionState;
using System.Windows.Forms;

namespace Wams.Admin.UI.services
{
    /// <summary>
    /// Summary description for SiteThumb
    /// </summary>
    public class SiteThumb : IHttpHandler, IRequiresSessionState
    {
        public System.Windows.Forms.WebBrowser Renderer;
        public Bitmap ImageOutput = null;

        public void ProcessRequest(HttpContext context)
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies["wamsUI.auth"];
            if (authCookie == null || string.IsNullOrEmpty(authCookie.Value)) throw new ApplicationException("Access denied.");
            if (!Auth.CheckToken(authCookie.Value, true)) throw new ApplicationException("Access denied.");

            int siteId = -1;
            if (string.IsNullOrEmpty(context.Request.QueryString["siteId"]) || !int.TryParse(context.Request.QueryString["siteId"], out siteId)) return;

            WamsSettings settings = WamsSettings.Load(Utils.StorageAccount, Utils.ContainerName);
            var selectedSite = settings.Sites.Where(x=> x.Id == siteId).FirstOrDefault();

            if (selectedSite == null) return;

            string url = selectedSite.Url;
            if (string.IsNullOrEmpty(url)) return;

            var WorkerThread = new Thread(() =>
            {
                var Renderer = new WebBrowser();
                
                Renderer.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Renderer_DocumentCompleted);
                Renderer.Name = url.ToString();
                Renderer.Size = new Size(1024, 1024);
                Renderer.ScrollBarsEnabled = false; 
                Renderer.AllowNavigation = true;
                Renderer.Navigate(new Uri(url));
                Renderer.ScriptErrorsSuppressed = true;
                while (Renderer.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
                Renderer.Dispose();
            });
            WorkerThread.SetApartmentState(ApartmentState.STA);
            WorkerThread.Name = "SiteThumbnailGenerator";
            WorkerThread.Start();
            WorkerThread.Join(TimeSpan.FromSeconds(60));
            try { if (!Renderer.IsDisposed) Renderer.Dispose(); } catch {}

            if (ImageOutput != null)
            {
                context.Response.ContentType = "image/png";
                ImageOutput.Save(context.Response.OutputStream, ImageFormat.Png);
            }
        }

        void Renderer_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            Bitmap docImage = new Bitmap(1024, 1024);
            WebBrowser renderer = ((WebBrowser)sender);
            renderer.DrawToBitmap(docImage, new Rectangle(renderer.Location.X, renderer.Location.Y, renderer.Width, renderer.Height));
            ImageOutput = new Bitmap(docImage, new Size(300, 300));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}